package logic

import (
	"context"
	"fmt"
	"shop_srv/model/mysql"
	"shop_srv/model/redis"

	"shop_srv/internal/svc"
	"shop_srv/shop"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *shop.AddCartRequest) (*shop.AddCartResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Good{}
	err := g.GetGood(int(in.GoodId))
	if err != nil {
		return nil, fmt.Errorf("信息获取失败")
	}
	if g.ID == 0 {
		return nil, fmt.Errorf("商品不存在")
	}

	stock := redis.GetGoodStock(in.GoodId)
	if stock < in.Num {
		return nil, fmt.Errorf("商品库存不足")
	}

	if !redis.CartExist(in.UserId, in.GoodId) {
		if err = redis.UpdateNumBy(in.UserId, in.GoodId, in.Num); err != nil {
			logx.Error("添加购物车", err)
			return nil, err
		} else {
			cartMap := map[string]interface{}{
				"user_id":    in.UserId,
				"good_id":    in.GoodId,
				"good_title": g.GoodTitle,
				"good_price": g.GoodPrice,
				"good_num":   in.Num,
				"checked":    1,
			}
			if redis.AddCart(cartMap); err != nil {
				logx.Error("添加购物车失败", err)
				return nil, err
			}
		}
	}
	return &shop.AddCartResponse{Success: true}, nil
}
